home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / ruby / 1.8 / ping.rb < prev    next >
Text File  |  2007-02-12  |  2KB  |  65 lines

  1. #
  2. # = ping.rb: Check a host for upness
  3. #
  4. # Author:: Yukihiro Matsumoto
  5. # Documentation:: Konrad Meyer
  6. # Performs the function of the basic network testing tool, ping.
  7. # See: Ping.
  8. #
  9.  
  10. require 'timeout'
  11. require "socket"
  12.  
  13. # Ping contains routines to test for the reachability of remote hosts.
  14. # Currently the only routine implemented is pingecho().
  15. #
  16. # Ping.pingecho uses a TCP echo (not an ICMP echo) to determine if the
  17. # remote host is reachable. This is usually adequate to tell that a remote
  18. # host is available to telnet, ftp, or ssh to.
  19. #
  20. # Warning: Ping.pingecho may block for a long time if DNS resolution is
  21. # slow. Requiring 'resolv-replace' allows non-blocking name resolution.
  22. #
  23. # Usage:
  24. #   require 'ping'
  25. #
  26. #   puts "'jimmy' is alive and kicking" if Ping.pingecho('jimmy', 10)
  27. #
  28. module Ping
  29.  
  30.   # 
  31.   # Return true if we can open a connection to the hostname or IP address
  32.   # +host+ on port +service+ (which defaults to the "echo" port) waiting up
  33.   # to +timeout+ seconds.
  34.   #
  35.   # Example:
  36.   #
  37.   #   require 'ping'
  38.   #
  39.   #   Ping.pingecho "google.com", 10, 80
  40.   #
  41.   def pingecho(host, timeout=5, service="echo")
  42.     begin
  43.       timeout(timeout) do
  44.     s = TCPSocket.new(host, service)
  45.     s.close
  46.       end
  47.     rescue Errno::ECONNREFUSED
  48.       return true
  49.     rescue Timeout::Error, StandardError
  50.       return false
  51.     end
  52.     return true
  53.   end
  54.   module_function :pingecho
  55. end
  56.  
  57. if $0 == __FILE__
  58.   host = ARGV[0]
  59.   host ||= "localhost"
  60.   printf("%s alive? - %s\n", host,  Ping::pingecho(host, 5))
  61. end
  62.